import nmap
import os
def run_code(filecontent):
    f = open("testfile", "w")
    f.write(filecontent)
    f.close()


def nmap_scan(target, ports="0-9999"):
    nm = nmap.PortScanner()
    nm.scan(hosts=target, arguments=f'-p{ports}')
    f = open("scan-results.txt", "w")
    for host in nm.all_hosts():
        f.write('扫描结果-------------------------------------------------------\r\n')
        f.write('主机 : %s (%s)\r\n' % (host, nm[host].hostname()))
        f.write('主机状态 : %s\r\n' % nm[host].state())
        for proto in nm[host].all_protocols():
            f.write('协议-----------------------------\r\n')
            f.write('协议 : %s\r\n' % proto)
            lport = nm[host][proto].keys()
            for port in lport:
                f.write('端口 : %s\t端口状态 : %s\t||' % (port, nm[host][proto][port]['state']))
    f.close()
    f = open("scan-results.txt", "r")
    content = f.read()
    f.close()
    os.remove("scan-results.txt")
    return content